package com.lollipop.synthential.proxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: J.K
 * @Date: 2021-03-08 14:32
 * @Description: Cglib动态代理：基于继承
 */
public class CglibProxy implements MethodInterceptor {

    /**
     * 被代理的原始对象
     */
    private Object obj;

    public static void main(String[] args) {
        CglibProxy proxy = new CglibProxy();
        DoService doService = new DoService();
        DoService service = (DoService) proxy.createProxy(doService);
        service.doProcess();
    }

    /**
     * 创建代理类
     *
     * @param target
     * @return
     */
    private Object createProxy(Object target) {
        this.obj = target;

        // 增强代理对象
        Enhancer enhancer = new Enhancer();

        // 设置代理目标
        enhancer.setSuperclass(this.obj.getClass());

        // 设置回调
        enhancer.setCallback(this);

        // 设置类加载器
        enhancer.setClassLoader(target.getClass().getClassLoader());

        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        Object result;
        doBefore();
        result = methodProxy.invokeSuper(o, objects);
        doAfter();
        return result;
    }

    private void doBefore() {
        System.out.println("前置增强...");
    }

    private void doAfter() {
        System.out.println("后置增强...");
    }

    /**
     * 代表某个业务
     */
    public static class DoService {
        public void doProcess() {
            System.out.println("处理业务~~~");
        }
    }
}
